{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import geoviews as gv\n",
    "\n",
    "from geoviews import opts\n",
    "from bokeh.sampledata.airport_routes import airports, routes\n",
    "\n",
    "gv.extension('bokeh')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Define data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Count the number of connections from each airport\n",
    "counts = routes.groupby('SourceID')[['Stops']].count().reset_index().rename(columns={'Stops': 'Connections'})\n",
    "airports_df = pd.merge(airports, counts, left_on='AirportID', right_on='SourceID', how='left')\n",
    "\n",
    "# Select only US mainland airports & convert from Mercator to Latitudes/Longitudes\n",
    "airport_points = gv.Points(airports_df, ['Longitude', 'Latitude']).select(Longitude=(-170, -50), Latitude=(0, 50))\n",
    "\n",
    "# Declare nodes, graph and tiles\n",
    "nodes = gv.Nodes(airport_points, ['Longitude', 'Latitude', 'AirportID'],\n",
    "                 ['Name', 'City', 'Connections'])\n",
    "graph = gv.Graph((routes, nodes), ['SourceID', 'DestinationID'], ['Source', 'Destination'])\n",
    "tiles = gv.tile_sources.Wikipedia\n",
    "\n",
    "# Select 50 busiest airports\n",
    "busiest = list(routes.groupby('SourceID').count().sort_values('Stops').iloc[-50:].index.values)\n",
    "busiest_airports = graph.select(AirportID=busiest, selection_mode='nodes')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "(tiles * busiest_airports).opts(\n",
    "    opts.Graph(edge_selection_line_color='black', edge_hover_line_color='red',\n",
    "               edge_line_width=1, edge_line_alpha=0.01, edge_nonselection_line_alpha=0.01,\n",
    "               padding=0.1, width=800, height=600))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
